const Router = require('koa-router')
const mysql = require('../util/mysql/mysql')
const { SUCCESS, FAIL, PARAM_NOT_COMPLETE } = require('../util/respone/index')

let questions = new Router()

function checkForm(params,checkType = '*') {
  // 拼接 查询数据库语句 
  let { id, username = '', emails = '', c_type = null } = params
  if (id) {
    return `SELECT ${checkType} FROM questions WHERE id = ${id}`
  } else if (username || emails) {
    return `SELECT ${checkType} FROM questions WHERE username LIKE '%${username}%' and emails LIKE '%${emails}%'`
  } else {
    return `SELECT ${checkType} FROM questions`
  }
}

// 获取常见问题信息
questions.get('/questions', async (ctx, next) => {
  // 用户post过来的数据
  let { pageSize = 10, pageNum = 1} = ctx.query;

  // 拼接 查询数据库 语句
  let checkSql = checkForm(ctx.query) + ` limit ${(pageNum - 1) * pageSize}, ${pageSize}`

  // 拼接 查询总数 语句
  let checkTotalSql = checkForm(ctx.query,'COUNT(*)')
  
  let outObj = { pageSize, pageNum }; // 向外输出数据的obj
  let isSuccess = true; // 数据库中 查询操作成功标签
  // -------数据库操作------
  // 查询数据库中数据
  await mysql.check(checkSql)
    .then(async res => {
      outObj.dataList = res
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx,'查询常见问题出错!')
    })
  
  if(!isSuccess) return // 如果查询出错则不需要执行下面查询
    
  //查询总数
  await mysql.check(checkTotalSql)
    .then(async res => {
      outObj.total = res[0]['COUNT(*)']
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx,'查询常见问题总数出错!')
    })
  
  if (isSuccess) {
    await SUCCESS(ctx, outObj, "获取常见问题成功！")
  }
})

// 添加 常见问题
questions.post('/questions', async (ctx, next) => {
  // 用户post过来的数据
  let postParams = ctx.request.body;

  if (!postParams.username || !postParams.emails) { // 如果没有传入username 和 emails 则弹出 错误：请求参数缺失
    return await PARAM_NOT_COMPLETE(ctx)
  }

  // 拼接 添加数据 语句
  let keysArr = Object.keys(postParams)
  let VALUES = setValue(keysArr.length)
  // -------数据库操作------
  let addSql = `INSERT INTO questions(${keysArr.join(',')}) VALUES(${VALUES})`
  let addSqlParams = [...Object.values(postParams)]
  await mysql.add(addSql, addSqlParams)
    .then(async res => {
      await SUCCESS(ctx,{},"添加常见问题成功！")
    })
    .catch(async err => {
      return await FAIL(ctx, '添加常见问题出错!')
  })
})

function setValue(length) {
  let VALUES = ''
  for (let i = 0; i < length; i++){
    VALUES = VALUES + '?,'
  }
  VALUES = VALUES.substring(0,VALUES.length-1)
  return VALUES
}

// 删除常见问题
questions.delete('/questions', async (ctx, next) => {
  let { id } = ctx.request.body

  if (!id) { // 如果没有传入id 则弹出 错误：请求参数缺失
    return await PARAM_NOT_COMPLETE(ctx)
  }
  
  // -----数据库操作-------
  let delSql = `DELETE FROM questions WHERE id = "${id}"`
  await mysql.delete(delSql)
    .then(async res => {
      await SUCCESS(ctx,{},"删除常见问题成功！")
    })
    .catch(async err => {
      return await FAIL(ctx, '删除常见问题出错!')
  })
})

module.exports = { questions }